package com.bhs.sansonglogistics.ui.orderDispose;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.AbnormalOrderDetailBean;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.PictureSelectAdapter;
import com.bhs.sansonglogistics.ui.adapter.PictureShowAdapter;
import com.bhs.sansonglogistics.ui.adapter.PictureShowAdapter3;
import com.bhs.sansonglogistics.utils.DateUtils;
import com.bhs.sansonglogistics.utils.EditTextUtil;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.view.Watermark;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.util.SmartGlideImageLoader;

import java.util.Arrays;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 异常订单处理
 */
public class AbnormalOrderDisposeActivity extends BaseActivity implements View.OnClickListener, NetCallBack, TextWatcher {

    private EditText mEtAmountPaid;
    private EditText mEtDescribe;
    private TextView mTvDescribeWordCount;
    private RecyclerView mRvVoucher;
    private Button mBtnSubmit;
    private int id;
    private PictureSelectAdapter selectAdapter;
    private TextView mTvComplaintTime;
    private TextView mTvDescribe;
    private RecyclerView mRvComplaint;
    private TextView mTvClient;
    private TextView mTvPhone;
    private TextView mTvType;
    private TextView mTvGoodsName;
    private TextView mTvDeliveryType;
    private TextView mTvDispatchingType;
    private TextView mTvOrderNumber;

    private PictureShowAdapter3 showAdapter;
    private TextView mTvDepartureAddress;
    private TextView mTvDeliveryAddress;

    @Override
    public int initLayout() {
        return R.layout.activity_abnormal_order_dispose;
    }

    @Override
    public void initView() {
        id = getIntent().getIntExtra("id", 0);
        TextView mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("处理详情");
        mEtAmountPaid = findViewById(R.id.et_amount_paid);
        mEtDescribe = findViewById(R.id.et_describe);
        mTvDescribeWordCount = findViewById(R.id.tv_describe_word_count);
        mRvVoucher = findViewById(R.id.rv_voucher);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnSubmit.setOnClickListener(this);
        mEtDescribe.addTextChangedListener(this);
        mTvComplaintTime = findViewById(R.id.tv_complaint_time);
        mTvDescribe = findViewById(R.id.tv_describe);
        mRvComplaint = findViewById(R.id.rv_complaint);
        mTvClient = findViewById(R.id.tv_client);
        mTvPhone = findViewById(R.id.tv_phone);
        mTvType = findViewById(R.id.tv_type);
        mTvGoodsName = findViewById(R.id.tv_goods_name);
        mTvDeliveryType = findViewById(R.id.tv_delivery_type);
        mTvDispatchingType = findViewById(R.id.tv_dispatching_type);
        mTvOrderNumber = findViewById(R.id.tv_order_number);
        mTvDepartureAddress = findViewById(R.id.tv_departure_address);
        mTvDeliveryAddress = findViewById(R.id.tv_delivery_address);
        mTvPhone.setOnClickListener(this);
        findViewById(R.id.iv_phone).setOnClickListener(this);
    }

    @Override
    public void initData() {
        selectAdapter = new PictureSelectAdapter(3, this);
        mRvVoucher.setAdapter(selectAdapter);
        mRvVoucher.setLayoutManager(new GridLayoutManager(this, 3));
        mEtAmountPaid.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                EditTextUtil.keepTwoDecimals(mEtAmountPaid, 7);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mEtDescribe.setFilters(MyUtils.inputFilters(mActivity, 300));
        loadingPopupShow();
        networkRequest(netApi.get_abnormal_info(id), this);
        mEtDescribe.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN||event.getAction()==MotionEvent.ACTION_MOVE){
                    //这句话说的意思告诉父View我自己的事件我自己处理
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.btn_submit) {
            Map<String, Object> map = new ArrayMap<>();
            map.put("id", id);
            map.put("money", TextUtils.isEmpty(mEtAmountPaid.getText().toString()) ? 0 : mEtAmountPaid.getText().toString());
            map.put("imgs", selectAdapter.CommaSplice());
            map.put("content", mEtDescribe.getText().toString());
            networkRequest(netApi.handle_abnormal_handle(map), this, 666);
        }else {
            MyUtils.callPhone(this,mTvPhone.getText().toString());
        }
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        loadingPopupDismiss();
        if (requestCode == 0) {
            AbnormalOrderDetailBean detailBean = new Gson().fromJson(json, AbnormalOrderDetailBean.class);
            if (detailBean.isStatus()) {
                mTvDescribe.setText(detailBean.getData().getContent());
                mTvComplaintTime.setText(DateUtils.getTime(detailBean.getData().getCreate_time()));
                mTvClient.setText(detailBean.getData().getCargo_info().getNickname());
                mTvPhone.setText(detailBean.getData().getCargo_info().getMobile());
                mTvType.setText(detailBean.getData().getType());
                AbnormalOrderDetailBean.DataDTO.DeliverInfoDTO info = detailBean.getData().getDeliver_info();
                mTvGoodsName.setText(String.format("货物信息：%s/%s件/%s吨/%s立方", info.getGoods_name(), info.getGoods_number(),
                        MyUtils.checkPoint(info.getGoods_weight()), MyUtils.checkPoint(info.getGoods_volume())));
                mTvDeliveryType.setText(MyUtils.getDeliveryType(info.getJiaohuo_type()));
                mTvDispatchingType.setText(MyUtils.getDeliveryType(info.getPeisong_type()));
                mTvOrderNumber.setText(info.getDeliver_sn());
                if (TextUtils.isEmpty(info.getPickup_province())) {
                    mTvDepartureAddress.setText(String.format("%s-%s", info.getPickup_city(), info.getPickup_address()));
                } else {
                    mTvDepartureAddress.setText(String.format("%s-%s-%s", info.getPickup_province(), info.getPickup_city(), info.getPickup_address()));
                }

                if (TextUtils.isEmpty(info.getReceive_province())) {
                    mTvDeliveryAddress.setText(String.format("%s-%s", info.getReceive_city(), info.getReceive_address()));
                } else {
                    mTvDeliveryAddress.setText(String.format("%s-%s-%s", info.getReceive_city(), info.getReceive_city(), info.getReceive_address()));
                }
                if (!TextUtils.isEmpty(detailBean.getData().getImgs())) {
                    Object[] imgData = detailBean.getData().getImgs().split("\\|\\|");
                    showAdapter = new PictureShowAdapter3(R.layout.item_picture2, Arrays.asList(imgData));
                    showAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                            BasePopupView dialog = new XPopup.Builder(mContext)
                                    .asImageViewer(view.findViewById(R.id.iv_picture), position, Arrays.asList(imgData), null, new SmartGlideImageLoader())
                                    .isShowSaveButton(false)
                                    .show();
                        }
                    });
                    mRvComplaint.setAdapter(showAdapter);
                    mRvComplaint.setLayoutManager(new GridLayoutManager(mActivity, 3));
                }
            }
        } else if (requestCode == 666) {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            if (bean.isStatus()) {
                ToastUtil.show("提交成功");
                finish();
            } else {
                ToastUtil.show(bean.getMsg());
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        mTvDescribeWordCount.setText(String.format("%s/300", s.length()));
        verify();
    }

    private void verify() {
        boolean verify = !TextUtils.isEmpty(mEtDescribe.getText().toString());
        mBtnSubmit.setEnabled(verify);
        mBtnSubmit.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }
}